package com.test.google.app.common;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.test.google.app.action.SysAction;
import com.test.google.app.domain.RequestInfo;
import com.test.google.app.util.Md5Util;

public class UserIntorceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler) throws Exception {
		String[] noFilterUri = new String[] {"/sys/login.do", "/sys/doLogin.do", "/gaeTask/"};
		String requestUri = request.getRequestURI();
		for (String uri : noFilterUri) {
			if (requestUri.contains(uri)) {
				return true;
			}
		}
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (Cookie c : cookies) {
				if (c.getName().equals(SysAction.COOKIE_KEY_LOGIN_FLAG)) {
					String[] ss = c.getValue().split("-");
					if (ss.length == 2 && System.currentTimeMillis() - 
							Long.parseLong(ss[1]) <= SysAction.SESSION_TTL) {
						Cookie c2 = new Cookie(SysAction.COOKIE_KEY_LOGIN_FLAG, 
								Md5Util.md5(RequestInfo.getIp(request)) + "-" + System.currentTimeMillis());
						c2.setPath("/");
						response.addCookie(c);
						return true;
					}
				}
			}
		}
		response.sendRedirect("/haottiis/sys/login.do");
		return false;
	}

}
